<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" ref="queryRef" :model="queryParams" label-width="auto" :inline="true">  
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="queryParams.title" style="width:100%" placeholder="输入标题"></el-input>
      </el-form-item>
       <el-form-item label="用户类型" prop="platformType">
        <el-select v-model="queryParams.platformType" style="width: 100%;" placeholder="请选择用户类型">
              <el-option
                  v-for="item in platformTypeListRef"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker v-model="dateObj.beginCreateDate" type="daterange" range-separator="-" start-placeholder="起始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="消息状态" prop="status">
        <el-select v-model="queryParams.status" style="width:100%" placeholder="选择状态">
          <el-option label="待发布" value="5"></el-option>
          <el-option label="已发布" value="10"></el-option>
          <el-option label="已撤销" value="15"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
     <div style="display: flex; justify-content: flex-end;" v-if="userInfo.userType==1">  
      <el-button type="primary" size="small" :icon="Document" style="margin-left: 20px;" @click="batchTap(1)">批量删除</el-button>
      <el-button type="primary" size="small" :icon="FolderDelete" style="margin-left: 20px;" @click="batchTap(2)">批量撤销</el-button>
      <el-button type="primary" size="small" :icon="Plus" @click="addClick" style="margin:0 20px;">发布广告</el-button>
    </div>
    <Table ref="tableRef" v-bind="table"  @pageChange="onTablePageChange" @editPermissions="editPermissions" @editPermissionsInfo="editPermissionsInfo" @deleteBox="deleteBox"  @revokeBox="revokeBox"></Table>
  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import { onActivated, reactive, ref,computed } from 'vue';
import { getPlatformNotices,deleteIds,revoke } from '@/api/platformNotices/index'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus';
import useUserStore from '@/store/modules/user';
import { Plus,Grid,FolderDelete,Document,DocumentChecked,Edit,Delete } from '@element-plus/icons-vue'
const dateObj=ref({
  beginCreateDate:null,
})
const queryRef=ref(null)
const data = reactive({
  form: {},
  queryParams: {
    msgTitle: '',
    status:'',
    platformType:null,
    beginPublishDate: '',
    endPublishDate:'',
    pageNum: 1,
    pageSize: 10,
  },
});
const { queryParams, form } = toRefs(data);
const businessTypeList = {5:'货代',10:'集装箱公司',15:'箱贸易',20:'集卡车队',25:'堆场',30:'所有用户'}
const platformTypeListRef =ref([
  {
    label:'货代',
    value:5
  },{
    label:'集装箱公司',
    value:10
  },{
    label:'箱贸易',
    value:15
  },{
    label:'集卡车队',
    value:20
  },{
    label:'堆场',
    value:25
  },{
    label:'所有用户',
    value:30
  }
])

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'title', colWidth: '150', title: '公告标题',type: '<a>',command: 'editPermissionsInfo', isCheck: true },
    { key: 'platformType', colWidth: '100', title: '接收用户类型', type: 'filter', filter: businessTypeList, isCheck: true },
    { key: 'status', colWidth: '120', title: '状态',type: 'platformMsg', isCheck: true },
    { key: 'publishDate', colWidth: '150', title: '发布时间',type: 'checkTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: false,
      buttons: [
        {
          icon: 'Edit',
          type: 0,  
          command: 'editPermissions',
          content: '编辑',
        },
        {
          icon: 'Document',
          type: 0, 
          command: 'revokeBox',
          content: '撤销',
          isShow: (row: any) => {
            return  row.status == 5 || row.status == 10;          
          },
        },
         {
          icon: 'Delete',
          type: 0,  //企业用户 1  企业账号 0 
          command: 'deleteBox',
          content: '删除',
          isShow: (row: any) => {
            return  row.status == 15;          
          },
        }
      ]
    }
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});
const userInfo=ref({})
onActivated(() => {
    userInfo.value = useUserStore().getUser()
  getTableData()
})

// 获取表格数据
function getTableData() {
  if (dateObj.value.beginCreateDate) {
    queryParams.value.beginPublishDate = dateObj.value.beginCreateDate[0]
    queryParams.value.endPublishDate = dateObj.value.beginCreateDate[1]
  }
  table.config.loading = true;
  // 列表
  getPlatformNotices(JSON.stringify(queryParams.value)).then((res: any) => {
    table.data = res.data.list;
    table.config.total = res.data.total;
    table.config.loading = false;
    if(userInfo.value.userType==1){
      table.header.forEach((item)=>{
      if(item.key=='operate'){
        item.isCheck=true
      }
    })
    }
  }).catch((err) => {
    console.log(err)
  })
}
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
// 批量操作
const batchTap= (type) => {
  //type  1删除  2撤销
     let row=selection.value
  if(type==1){
    if(row.length==0){
      ElMessage.warning('请选择删除的数据');
        return false
    }
    let billStatusIn=false
    //获取账单类型
    table.data.map(item => {
      row.map(itemInfo => {
        if(item.id == itemInfo){
          // attrType.push(item.refType)
          if(item.status!=15){
            billStatusIn = true
          }
        }
      })
    })
    if(billStatusIn)return ElMessage.warning('只能删除已撤销状态');
    deleteBox(row)
  }else if(type==2){
    if(row.length==0){
      ElMessage.warning('请选择撤销的数据');
        return false
    }
     let billStatusIn=false
    //获取账单类型
    table.data.map(item => {
      row.map(itemInfo => {
        if(item.id == itemInfo){
          if(item.status==15){
            billStatusIn = true
          }
        }
      })
    })
    if(billStatusIn)return ElMessage.warning('只能撤销已发布和待发布的状态');
    revokeBox(row)
  }
}
//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '您确定要删除当前的公告信息？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data=[]
      if(row?.id){
        //单独删除
        data.push(row.id)
      }else{
        //批量
        data=row
      }
      deleteIds(data).then((res) => {
        ElMessage.success('删除成功')
        getTableData()
      })
    })
}
//撤销操作
const revokeBox = (row) => {
  ElMessageBox.confirm(
    '您确定要撤销当前的公告信息？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data=[]
      if(row?.id){
        //单独撤销
        data.push(row.id)
      }else{
        //批量
        data=row
      }
      revoke(data).then((res) => {
        ElMessage.success('撤销成功')
        getTableData()
      })
    })
}
const router = useRouter();
const editPermissions = (row) => {
    router.push({ 
      path: '/webInfoManage/webAnnouncementInfo', 
      query: { 
        id:row.id,
        type:'edit'
      } 
    })
}
//详情

const editPermissionsInfo = (row) => {
    router.push({ 
      path: '/webInfoManage/webAnnouncementInfo', 
      query: { 
        id:row.id,
        type:'dataInfo'
      } 
    })
}
const addClick=()=>{
  router.push({ 
      path: '/webInfoManage/webAnnouncementInfo', 
      query: { 
        type:'add'
      } 
    })
}
const handleReSet = () => {
  queryRef.value.resetFields()
  dateObj.value.beginCreateDate=null
  queryParams.value.beginPublishDate = ''
  queryParams.value.endPublishDate = ''
  getTableData();
};

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  queryParams.value.pageNum = page.pageNum;
  queryParams.value.pageSize = page.pageSize;
  getTableData();
};

</script>
<style scoped>
.choose-item-2 {
  margin-left: 20px;
}

.choose-item-3 {
  display: block;
  margin-left: 20px;
}
</style>